import com.sun.tools.attach.VirtualMachine;
import com.sun.tools.attach.VirtualMachineDescriptor;

import java.util.ArrayList;
import java.util.List;

public class AgentStarter {
    public static void main(String[] args) {

        VirtualMachine vm;
        List<VirtualMachineDescriptor> listAfter = null;
        List<VirtualMachineDescriptor> listBefore = VirtualMachine.list();
        while (listAfter == null || (listAfter.size() != listBefore.size())) {

            try {
                listAfter = new ArrayList<>();
                for (VirtualMachineDescriptor vmd : listBefore) {
                    if ((vmd.displayName().contains("exa") || vmd.displayName().contains("servlet"))) {
                        vm = VirtualMachine.attach(vmd);
                        if (null != vm) {
//                            vm.loadAgent("E:/code/jar/agent.jar");
//                            vm.loadAgent("E:/code/agent/out/artifacts/agent_jar/agent.jar");
                            vm.loadAgent("F:/code/java_agent_asm/target/java_agent_asm-1.0-SNAPSHOT.jar");
                            vm.detach();
                        }
                        Thread.sleep(1000);
                        System.out.println("i find a vm,agent.jar was injected.");
                    }
                    listAfter.add(vmd);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        System.out.println("end!");
    }
}
